package project.ia04.agents.gui;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import project.ia04.utils.Data;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class XAgentInitNewGameBehaviour extends Behaviour {

	private int state = 0;
	private String title;
	private String genre;
	private String type;
	private float cost;
	
	
	
	public XAgentInitNewGameBehaviour(String title, String genre, String type,float cost) {
		this.title = title;
		this.genre = genre;
		this.type = type;
		this.cost = cost;
	}

	@Override
	public void action() {
		ACLMessage message;
		switch(state) {
		case 0 :
			System.out.println("XAgent --> XAgentInitNewGameBehaviour (Send)");
			message = new ACLMessage(ACLMessage.REQUEST);
			message.addReceiver(((XAgent)myAgent).getEnvAgent());
			message.setConversationId(Data.INITGUINEWGAME);
			message.setContent(serialize());
			myAgent.send(message);
			state++;
			break;
		case 1 :
			MessageTemplate template = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
								MessageTemplate.MatchConversationId(Data.INITGUINEWGAME));
			message = myAgent.receive(template);
			if(message != null){
				System.out.println("XAgent --> XAgentInitNewGameBehaviour (Reception)");
				((XAgent)myAgent).initGameProp(message.getConversationId(),deserialize(message.getContent()));
				state++;
			}
			else 
				block();
			
			break;
		default :
			block();
		}
		
	}

	private Map<String,Object> deserialize(String content) {
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> map;
		try {
			map = mapper.readValue(content,Map.class);
			return map;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean done() {
		return state == 2;
	}
	
	private String serialize(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("title",title);
		map.put("genre",genre);
		map.put("type",type);
		map.put("cost",cost);
		StringWriter sw = new StringWriter();
		ObjectMapper mapper = new ObjectMapper();
		try{
			mapper.writeValue(sw,map);
		}
		catch(IOException ex){
			ex.printStackTrace();
		}
		return sw.toString();
	}

}
